package com.kantboot.api.varcode.repository;

import com.kantboot.api.varcode.domain.dto.ApiVarCodeSearchDTO;
import com.kantboot.api.varcode.domain.entity.ApiVarCode;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface ApiVarCodeRepository extends JpaRepository<ApiVarCode,Long> {

    /**
     * 根据类型编码、场景编码、接收人获取验证码
     * @param typeCode 类型编码
     * @param sceneCode 场景编码
     * @param to 接收人
     * @return 结果
     */
    @Query("""
        FROM ApiVarCode a WHERE a.typeCode = :typeCode AND a.sceneCode = :sceneCode AND a.to = :to AND a.value = :value
        ORDER BY a.id DESC limit 1
        """
    )
    ApiVarCode findByTypeCodeAndSceneCodeAndToAndValue(
            @Param("typeCode") String typeCode,
            @Param("sceneCode") String sceneCode,
            @Param("to") String to,
            @Param("value") String value);

    /**
     * getBodyData
     */
    @Query("""
    FROM ApiVarCode AS p
    WHERE
    (:#{#param.typeCode} IS NULL OR :#{#param.typeCode} = '' OR p.typeCode = :#{#param.typeCode})
    AND (:#{#param.sceneCode} IS NULL OR :#{#param.sceneCode} = '' OR p.sceneCode = :#{#param.sceneCode})
    AND (:#{#param.to} IS NULL OR :#{#param.to} = '' OR p.to = :#{#param.to})
    AND (:#{#param.value} IS NULL OR :#{#param.value} = '' OR p.value = :#{#param.value})
    ORDER BY p.id DESC
    """)
    Page<ApiVarCode> getBodyData(
            @Param("param") ApiVarCodeSearchDTO param,
            Pageable pageable);

}
